const Promise = require('bluebird');
const JiraTool = require('../Tools/JiraTool');
const Pool = require('../Tools/Pool');

const { jira, user } = require('../Configs');

let request = require('request');
request = Promise.promisifyAll(request);

const { JIRA_HOST } = jira;

/**
 * Jira相关请求和数据库操作
 */
class JiraModel {

  /**
   * 从数据库中获取最新的一条Jira数据
   */
  async getJiraSql() {
    let sql = 'SELECT * FROM jira ORDER BY id DESC LIMIT 1';
    let data = await Pool.queryAsync(sql);
    let ret = data[0];
    for (let i in ret) {
      if (typeof ret[i] == 'string') {
        ret[i] = JSON.parse(ret[i])
      }
    };
    return ret;
  }

  /**
   * 根据传入JQL从Jira服务器上获取相关Bug数据
   */
  async getBugByJql(params) {
    let api = `${JIRA_HOST}/rest/api/2/search?maxResults=0`
    if (params) {
      api = JiraTool.addParams(api, params);
    };
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  };

  /**
   * 根据传入Project_ID获取相关项目数据，
   * 如不传入参数则获取所有
   */
  async getProjectById(id) {
    let api = `${JIRA_HOST}/rest/api/2/project`;
    if (id) {
      api += `/${id}`;
    };
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  }

  /**
   * 根据传入Component_ID获取相关模块数据
   */
  async getComponentById(id) {
    let api = `${JIRA_HOST}/rest/api/2/component/${id}/relatedIssueCounts`;
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  }

  /**
   * 根据传入Project_ID获取相关项目的版本信息
   */
  async getProjectVersionsById(id) {
    let api = `${JIRA_HOST}/rest/api/2/project/${id}/versions`;
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  }

  async saveToSql(data) {
    let keys = [];
    let args = [];
    for (let i in data) {
      keys.push(i);
      if (typeof data[i] == 'object') {
        data[i] = JSON.stringify(data[i]);
      };
      args.push(data[i]);
    };
    let sqlKeysStr = keys.join(',');
    let sqlArgsStr = [];
    for (let i in keys) {
      sqlArgsStr.push('?');
    };
    sqlArgsStr = sqlArgsStr.join(',');
    let sql = `INSERT INTO jira (${sqlKeysStr}) VALUES (${sqlArgsStr})`;
    await Pool.queryAsync(sql, args);
  };

};

module.exports = new JiraModel();